package com._public._transitions 
{
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.display.GradientType;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.DisplacementMapFilter;
	import flash.filters.DisplacementMapFilterMode;
	import flash.geom.Matrix;
	import flash.geom.Point;
	/**
	 * 火焰特效
	 * @author Johnny Cheng
	 * @example
	 * var fire:Fire = new Fire(300,100);
	 * addChild(fire);
	 */
	public class Fire extends Sprite
	{
		private var _bitmapData:BitmapData;
		private var _offset:Point = new Point();
		private var _speed:Point;
		private var _density:Number;
		private var _strengh:Number;
		
		/**
		 * Construct
		 * @param	width   火焰宽度
		 * @param	height  火焰高度
		 * @param	spread  火舌顶部蔓延区域
		 * @param	hSpeed  火焰水平移动速度
		 * @param	vSpeed  火焰垂直移动速度
		 * @param	density 火焰密集度
		 * @param	strengh 火焰强度
		 */
		public function Fire(width:Number, height:Number, spread:Number = 30, hSpeed:Number = 0, vSpeed:Number = 6, density:Number = 20, strengh:Number = 100) 
		{
			_speed = new Point(-hSpeed, vSpeed);
			_density = density;
			_strengh = strengh;
			
			graphics.beginFill(0, 0);
			graphics.drawRect(0, 0, width, spread);
			var mat:Matrix = new Matrix();
			mat.createGradientBox(width, height - spread, Math.PI / 2);
			graphics.beginGradientFill(GradientType.LINEAR, [0x900000, 0x900000, 0xFF9900, 0xFFFD8A, 0xFFFFFF], [0, 1, 1, 1, 1], [0x00, 0xFF / 16, 0xFF * 2 / 6, 0xFF * 2 / 3, 0xFF], mat, SpreadMethod.PAD);
			graphics.drawRect(0, spread, width, height - spread);
			
			_bitmapData = new BitmapData(width, height);
			
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		
		private function enterFrameHandler(e:Event):void 
		{
			filters = [new DisplacementMapFilter(_bitmapData, new Point(), BitmapDataChannel.RED, BitmapDataChannel.RED, 10, _strengh, DisplacementMapFilterMode.CLAMP)];
			_offset = _offset.add(_speed);
			_bitmapData.perlinNoise(_density / 2, _density, 3, 0, false, true, 1, true, [_offset, _offset]);
		}
		
		/**
		 * 停止渲染，释放内存
		 */
		public function dispose():void
		{
			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
			_bitmapData.dispose();
		}
	}

}